﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;

namespace Admin.NET.Application;

/// <summary>
/// 检验项目服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class inspectionprojectService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<inspectionproject> _inspectionprojectRep;
    private readonly ISqlSugarClient _sqlSugarClient;
    private readonly SysDictTypeService _sysDictTypeService;

    public inspectionprojectService(SqlSugarRepository<inspectionproject> inspectionprojectRep, ISqlSugarClient sqlSugarClient, SysDictTypeService sysDictTypeService)
    {
        _inspectionprojectRep = inspectionprojectRep;
        _sqlSugarClient = sqlSugarClient;
        _sysDictTypeService = sysDictTypeService;
    }

    /// <summary>
    /// 分页查询检验项目 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询检验项目")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<inspectionprojectOutput>> Page(PageinspectionprojectInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _inspectionprojectRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.projectname.Contains(input.Keyword) || u.operation.Contains(input.Keyword) || u.Standard.Contains(input.Keyword) || u.unit.Contains(input.Keyword) || u.upperlimit.Contains(input.Keyword) || u.lowerlimit.Contains(input.Keyword) || u.remark.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.projectname), u => u.projectname.Contains(input.projectname.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.operation), u => u.operation.Contains(input.operation.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Standard), u => u.Standard.Contains(input.Standard.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.unit), u => u.unit.Contains(input.unit.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.upperlimit), u => u.upperlimit.Contains(input.upperlimit.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.lowerlimit), u => u.lowerlimit.Contains(input.lowerlimit.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.remark), u => u.remark.Contains(input.remark.Trim()))
            .WhereIF(input.inspectionid != null, u => u.inspectionid == input.inspectionid)
            .LeftJoin<inspectiontype>((u, inspection) => u.inspectionid == inspection.Id)
            .Select((u, inspection) => new inspectionprojectOutput
            {
                Id = u.Id,
                projectname = u.projectname,
                inspectionid = u.inspectionid,
                inspectionFkDisplayName = $"{inspection.inspectiontypename}",
                operation = u.operation,
                Standard = u.Standard,
                unit = u.unit,
                upperlimit = u.upperlimit,
                lowerlimit = u.lowerlimit,
                remark = u.remark,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取检验项目详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取检验项目详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<inspectionproject> Detail([FromQuery] QueryByIdinspectionprojectInput input)
    {
        return await _inspectionprojectRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加检验项目 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加检验项目")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddinspectionprojectInput input)
    {
        var entity = input.Adapt<inspectionproject>();
        return await _inspectionprojectRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新检验项目 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新检验项目")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateinspectionprojectInput input)
    {
        var entity = input.Adapt<inspectionproject>();
        await _inspectionprojectRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除检验项目 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除检验项目")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteinspectionprojectInput input)
    {
        var entity = await _inspectionprojectRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _inspectionprojectRep.FakeDeleteAsync(entity);   //假删除
        //await _inspectionprojectRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除检验项目 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除检验项目")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteinspectionprojectInput> input)
    {
        var exp = Expressionable.Create<inspectionproject>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _inspectionprojectRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _inspectionprojectRep.FakeDeleteAsync(list);   //假删除
        //return await _inspectionprojectRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDatainspectionprojectInput input)
    {
        var inspectionidData = await _inspectionprojectRep.Context.Queryable<inspectiontype>()
            .InnerJoinIF<inspectionproject>(input.FromPage, (u, r) => u.Id == r.inspectionid)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.inspectiontypename}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "inspectionid", inspectionidData },
        };
    }
    
    /// <summary>
    /// 导出检验项目记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出检验项目记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageinspectionprojectInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportinspectionprojectOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        var unitDictMap = _sysDictTypeService.GetDataList(new GetDataDictTypeInput { Code = "unit" }).Result.ToDictionary(x => x.Value, x => x.Label);
        list.ForEach(e => {
            e.unitDictLabel = unitDictMap.GetValueOrDefault(e.unit ?? "", e.unit);
        });
        return ExcelHelper.ExportTemplate(list, "检验项目导出记录");
    }
    
    /// <summary>
    /// 下载检验项目数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载检验项目数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportinspectionprojectOutput>(), "检验项目导入模板", (_, info) =>
        {
            if (nameof(ExportinspectionprojectOutput.inspectionFkDisplayName) == info.Name) return _inspectionprojectRep.Context.Queryable<inspectiontype>().Select(u => $"{u.inspectiontypename}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入检验项目记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入检验项目记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var unitDictMap = _sysDictTypeService.GetDataList(new GetDataDictTypeInput { Code = "unit" }).Result.ToDictionary(x => x.Label!, x => x.Value);
            var stream = ExcelHelper.ImportData<ImportinspectionprojectInput, inspectionproject>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 检验类型
                    var inspectionidLabelList = pageItems.Where(x => x.inspectionFkDisplayName != null).Select(x => x.inspectionFkDisplayName).Distinct().ToList();
                    if (inspectionidLabelList.Any()) {
                        var inspectionidLinkMap = _inspectionprojectRep.Context.Queryable<inspectiontype>().Where(u => inspectionidLabelList.Contains($"{u.inspectiontypename}")).ToList().ToDictionary(u => $"{u.inspectiontypename}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.inspectionid = inspectionidLinkMap.GetValueOrDefault(e.inspectionFkDisplayName ?? "");
                            if (e.inspectionid == null) e.Error = "检验类型链接失败";
                        });
                    }
                    
                    // 映射字典值
                    foreach(var item in pageItems) {
                        if (string.IsNullOrWhiteSpace(item.unitDictLabel)) continue;
                        item.unit = unitDictMap.GetValueOrDefault(item.unitDictLabel);
                        if (item.unit == null) item.Error = "单位字典映射失败";
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.inspectionid == null){
                            x.Error = "检验类型不能为空";
                            return false;
                        }
                        return true;
                    }).Adapt<List<inspectionproject>>();
                    
                    var storageable = _inspectionprojectRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.projectname?.Length > 32, "名称长度不能超过32个字符")
                        .SplitError(it => it.Item.operation?.Length > 32, "作业方式长度不能超过32个字符")
                        .SplitError(it => it.Item.Standard?.Length > 32, "标准值长度不能超过32个字符")
                        .SplitError(it => it.Item.unit?.Length > 32, "单位长度不能超过32个字符")
                        .SplitError(it => it.Item.upperlimit?.Length > 32, "上限值长度不能超过32个字符")
                        .SplitError(it => it.Item.lowerlimit?.Length > 32, "下限值长度不能超过32个字符")
                        .SplitError(it => it.Item.remark?.Length > 32, "备注长度不能超过32个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
